package uit.nfcmenu.activity;

import java.sql.Date;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Hashtable;
import java.util.List;

import uit.nfcmenu.R;
import uit.nfcmenu.db.model.ItemModel;
import uit.nfcmenu.db.model.OrderModel;
import uit.nfcmenu.db.model.OrderUIModel;
import uit.nfcmenu.manager.AssetsManager;
import uit.nfcmenu.manager.MenuManager;
import uit.nfcmenu.manager.OrderManager;
import uit.nfcmenu.util.CommConstant;
import uit.nfcmenu.view.OrderAdapter;
import uit.nfcmenu.webservice.MyException;
import uit.nfcmenu.webservice.WSMapping;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Chronometer;
import android.widget.Chronometer.OnChronometerTickListener;
import android.widget.ListView;
import android.widget.TextView;

public class OrderActivity extends BaseActivity implements OnClickListener {
	final String tag = OrderActivity.class.getSimpleName();
	

//	Button btnRefresh;
	ListView ordersListView;
/*	ArrayList<ItemModel> mItems;
	ArrayList<OrderModel> mOrders;*/
	OrderUIModel orderUI;
	TextView txtCurrentTime;
	TextView txtTitle;
	
	OrderAdapter adapter;
	String dateStr = null;
	
	boolean isFirstTime = true;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_order);

		initView();
		initData();
		initListener();
		
		isFirstTime = true;
	}
	
	@Override
	protected void onResume() {
		// Log.i(tag, "onResume()");
		super.onResume();
		int status = (isFirstTime) ? SHOW_MESSAGE_ON_DIALOG : SHOW_NOTHING;
		doIfMeetNetworkOrShowFailStatus(mContext, status, 
				new Runnable() { @Override public void run() {
						new RunLoader(new ChefOrderLoader()).run();
		}});
	}

	@Override
	protected Context getActivityContext() {
		return this;
	}

	@Override
	protected void initView() {
		super.initView();
		AssetsManager.setCommonAppFont(this, R.id.title);

		ordersListView = (ListView) findViewById(R.id.lvOrder);
		txtCurrentTime = (TextView) findViewById(R.id.txtCurrentTime);
		txtTitle = (TextView) findViewById(R.id.tvItem);
//		btnRefresh = (Button) findViewById(R.id.btnRefresh);

		Chronometer temp = (Chronometer) findViewById(R.id.chro);
		temp.start();
		temp.setOnChronometerTickListener(new OnChronometerTickListener() {

			@Override
			public void onChronometerTick(Chronometer chronometer) {
				Date date = new Date(System.currentTimeMillis());
				dateStr = date.toLocaleString();
				txtCurrentTime.setText(dateStr);
			}
		});

		if (CommConstant.isWaiter) { // waiter
			findViewById(R.id.btnMenu).setVisibility(View.VISIBLE);
		} else { // chef
			findViewById(R.id.btnCookedList).setVisibility(View.VISIBLE);
		}
	}

	protected void initData() {
		Log.i(tag, "initData() isWaiter="+CommConstant.isWaiter);
		
		String[] strings = mRes.getStringArray(R.array.status_array);
		String[] strings_language = mRes.getStringArray(
				R.array.status_array_language);
		CommConstant.initData(strings, strings_language);
	}

	protected void initListener() {
//		btnRefresh.setOnClickListener(OrderActivity.this);
		txtTitle.setOnClickListener(OrderActivity.this);
	}

	protected void changeLanguage(String language) { }

	public void onClick(View v) {
		switch (v.getId()) {
//		case R.id.btnRefresh:
//			doIfMeetNetworkOrShowFailStatus(mContext, SHOW_MESSAGE_ON_TOAST,
//					new Runnable() {
//						@Override
//						public void run() {
//							new RunLoader(new ChefOrderLoader()).run();
//						}
//					});
//			break;
		case R.id.tvItem:
			adapter.selectSort();
			break;
		}
	}

	@Override
	protected void onPause() {
		// Log.i(tag, "onPause()");
		super.onPause();
	}

	
	@Override
	public void notifyDataChanged() {
		Log.i(tag, "notifyDataChanged() " 
				+"WSMapping.isOrdersChanged="+WSMapping.isOrdersChanged
				+"isDataChangedOnView="+isDataChangedOnView);
		if (WSMapping.isOrdersChanged) {
			WSMapping.isOrdersChanged = false;
			doIfMeetNetworkOrShowFailStatus(mContext, SHOW_NOTHING,
					new Runnable() { @Override public void run() {
						new RunLoader(new ChefOrderLoader()).run();	
			}});
		}
	}
	
	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			ArrayList<OrderModel> orders = getOrders();
			updateView(orders);
		}
	};

	private void updateView(List<OrderModel> models) {
		 Log.e(tag, "updateView()"+models.size());

		ArrayList<OrderModel> orders = new ArrayList<OrderModel>();
		Hashtable<Integer, Integer> hash = new Hashtable<Integer, Integer>();
		// add models to view
	/*	int count = models.size();
		for (int i = 0; i < count; i++) {
			if (models.get(i) != null)
				hash.put(models.get(i).getId(), models.get(i).getTime());
		}*/
		for (int i = 0; i < models.size(); i++) {
			if (models.get(i) != null) {
				OrderModel model = models.get(i);
				// Log.i(tag, "loaded model " + model.toString());
				//FIXME order state // check
				int status = CommConstant.getStatus(model.getStatus());
				if (CommConstant.isWaiter){ // waiter
					if ((status != CommConstant.STATUS_DENY)
							&& (status != CommConstant.STATUS_DONE)
							&& (status != CommConstant.STATUS_SERVED)
							&& isOnDays(model.getDate())) {
						orders.add(model);
						Log.w(tag, "waiter add model " + model.toString());
					}
				} else { // chef
					if ((status == CommConstant.STATUS_NEW)
							|| (status == CommConstant.STATUS_COOKING)) {
						orders.add(model);
						Log.w(tag, "chef add model " + model.toString());
					}
				}
			}
		}
		orderUI.listorders = orders;
		Collections.reverse(orderUI.listorders);
		orderUI.setStoresValue();
		
		if (adapter == null) {
			adapter = new OrderAdapter(OrderActivity.this, orderUI);
			ordersListView.setAdapter(adapter);
		} else {
			adapter.setModels(orderUI);
			adapter.notifyDataSetChanged();
		}
//		Log.e(tag, "end updateView()");
	}
	

	public void onDataChanged() {
		Log.i(tag, "onDataChanged()");
		mHandler.sendEmptyMessage(1);
	}

	private class ChefOrderLoader extends BaseLoader {
		@Override
		protected Integer doInBackground(Void... params) {
			// get enus items
			orderUI = new OrderUIModel();
			ArrayList<ItemModel> items = getItems();
			if (items == null || items.size() == 0) {
				try {
					updateItemsFromServer();
					updateMenusFromServer();					

					items = getItems();
				} catch (MyException e) {
					e.printStackTrace();
				}
			}
			orderUI.listItem = items;
			MenuManager.getInstance(mContext).initMenu();
			
			// get orders
			//String date = dateStr.substring(0, 12);
			ArrayList<OrderModel> orders = getOrders();
//			if (orders == null || orders.size() == 0) {
				try {
					updateOrders();					
					orders = getOrders();
				} catch (MyException e) {
					e.printStackTrace();
				}
//			}
			orderUI.listorders = orders;

			return super.doInBackground(params);
		}

		@Override
		protected void onPostExecute(Integer result) {
			super.onPostExecute(result);
			if (orderUI.listorders != null) {
				updateView(orderUI.listorders);
			}
		}
	}
	
	@Override
	public void saveData() {
		Log.i(tag, "saveData()");
		new RunLoader(new ChefOrderSaving()).run();
		super.saveData();
	}
	
	private class ChefOrderSaving extends BaseLoader {
		
		@Override
		protected Integer doInBackground(Void... params) {
			OrderManager.getInstance(mContext).changeOrderStatus(adapter.getCurrentModel());
			return super.doInBackground(params);
		}
	}
	
	private boolean isOnDays(java.util.Date date) {
		// TODO remove
//		if (date != null && dateStr != null) {
//			String dateString = date.toLocaleString();
//			Log.i(tag, "dateString="+dateString+" vs dateStr="+dateStr);
//		}
		return true;
	}
}
